const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs'
};

// 娱乐城实体类字段定义
const entityDefinitions = {
    casino_rounds: {
        id: { type: 'bigint', nullable: false, primary: true },
        gameType: { type: 'tinyint', nullable: false, comment: '游戏类型：1-大小，2-赤壁，3-猜拳' },
        roundNumber: { type: 'int', nullable: false, comment: '期数编号' },
        startTime: { type: 'datetime', nullable: false, comment: '开始时间' },
        endTime: { type: 'datetime', nullable: false, comment: '结束时间' },
        status: { type: 'tinyint', nullable: false, default: 0, comment: '状态：0-下注中，1-开奖中，2-已结束' },
        resultData: { type: 'text', nullable: true, comment: '开奖结果数据' },
        totalGold: { type: 'bigint', nullable: false, default: 0, comment: '总金币下注' },
        totalSilver: { type: 'bigint', nullable: false, default: 0, comment: '总银币下注' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_dice_bets: {
        id: { type: 'bigint', nullable: false, primary: true },
        roundId: { type: 'bigint', nullable: false, comment: '期数ID' },
        userId: { type: 'bigint', nullable: false, comment: '用户ID' },
        characterId: { type: 'bigint', nullable: false, comment: '角色ID' },
        betType: { type: 'tinyint', nullable: false, comment: '下注类型：1-大，2-小，3-单，4-双，5-豹子' },
        betAmount: { type: 'bigint', nullable: false, comment: '下注金额' },
        currencyType: { type: 'tinyint', nullable: false, comment: '货币类型：1-金币，2-银币' },
        status: { type: 'tinyint', nullable: false, default: 0, comment: '状态：0-下注中，1-已开奖，2-已结算' },
        winAmount: { type: 'bigint', nullable: false, default: 0, comment: '中奖金额' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_chibi_bets: {
        id: { type: 'bigint', nullable: false, primary: true },
        roundId: { type: 'bigint', nullable: false, comment: '期数ID' },
        userId: { type: 'bigint', nullable: false, comment: '用户ID' },
        characterId: { type: 'bigint', nullable: false, comment: '角色ID' },
        side: { type: 'tinyint', nullable: false, comment: '支援国家：1-魏，2-蜀，3-吴' },
        betGold: { type: 'bigint', nullable: false, default: 0, comment: '金币下注' },
        betSilver: { type: 'bigint', nullable: false, default: 0, comment: '银币下注' },
        status: { type: 'tinyint', nullable: false, default: 0, comment: '状态：0-下注中，1-已开奖，2-已结算' },
        winGold: { type: 'bigint', nullable: false, default: 0, comment: '中奖金币' },
        winSilver: { type: 'bigint', nullable: false, default: 0, comment: '中奖银币' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_rock_paper_scissors: {
        id: { type: 'bigint', nullable: false, primary: true },
        challengerId: { type: 'bigint', nullable: false, comment: '发起者用户ID' },
        challengerName: { type: 'varchar(64)', nullable: false, comment: '发起者名称' },
        challengerValue: { type: 'tinyint', nullable: false, comment: '发起者出拳：1-石头，2-剪刀，3-布' },
        betAmount: { type: 'bigint', nullable: false, comment: '下注金额' },
        currencyType: { type: 'tinyint', nullable: false, comment: '货币类型：1-金币，2-银币' },
        status: { type: 'tinyint', nullable: false, default: 0, comment: '状态：0-等待应战，1-已应战，2-已结算' },
        responderId: { type: 'bigint', nullable: true, comment: '应战者用户ID' },
        responderName: { type: 'varchar(64)', nullable: true, comment: '应战者名称' },
        responderValue: { type: 'tinyint', nullable: true, comment: '应战者出拳' },
        winnerId: { type: 'bigint', nullable: true, comment: '获胜者用户ID' },
        winAmount: { type: 'bigint', nullable: false, default: 0, comment: '获胜金额' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_rankings: {
        id: { type: 'bigint', nullable: false, primary: true },
        userId: { type: 'bigint', nullable: false, comment: '用户ID' },
        userName: { type: 'varchar(64)', nullable: false, comment: '用户名称' },
        gameType: { type: 'tinyint', nullable: false, comment: '游戏类型：1-大小，2-赤壁，3-猜拳' },
        totalWin: { type: 'bigint', nullable: false, default: 0, comment: '总获胜金额' },
        winCount: { type: 'int', nullable: false, default: 0, comment: '获胜次数' },
        totalBet: { type: 'bigint', nullable: false, default: 0, comment: '总下注金额' },
        rankScore: { type: 'bigint', nullable: false, default: 0, comment: '排行分数' },
        title: { type: 'varchar(32)', nullable: true, comment: '称号' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_config: {
        id: { type: 'int', nullable: false, primary: true },
        configKey: { type: 'varchar(64)', nullable: false, comment: '配置键' },
        configValue: { type: 'text', nullable: false, comment: '配置值' },
        description: { type: 'varchar(255)', nullable: true, comment: '配置描述' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' },
        updatedAt: { type: 'datetime', nullable: false, comment: '更新时间' }
    },
    casino_operation_logs: {
        id: { type: 'bigint', nullable: false, primary: true },
        userId: { type: 'bigint', nullable: false, comment: '用户ID' },
        operationType: { type: 'varchar(32)', nullable: false, comment: '操作类型' },
        operationData: { type: 'text', nullable: true, comment: '操作数据' },
        ipAddress: { type: 'varchar(45)', nullable: true, comment: 'IP地址' },
        userAgent: { type: 'text', nullable: true, comment: '用户代理' },
        createdAt: { type: 'datetime', nullable: false, comment: '创建时间' }
    }
};

async function checkDatabaseSchema() {
    let connection;

    try {
        console.log('🔌 正在连接数据库...');
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！\n');

        // 获取所有娱乐城相关表
        console.log('📋 检查娱乐城相关表...');
        const [tables] = await connection.execute(`
      SELECT TABLE_NAME 
      FROM information_schema.TABLES 
      WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'casino_%'
      ORDER BY TABLE_NAME
    `, [dbConfig.database]);

        if (tables.length === 0) {
            console.log('❌ 未找到娱乐城相关表！');
            return;
        }

        console.log(`✅ 找到 ${tables.length} 个娱乐城相关表：`);
        tables.forEach(table => console.log(`   - ${table.TABLE_NAME}`));
        console.log('');

        // 检查每个表的结构
        for (const table of tables) {
            const tableName = table.TABLE_NAME;
            console.log(`🔍 检查表: ${tableName}`);

            // 获取表的列信息
            const [columns] = await connection.execute(`
        SELECT 
          COLUMN_NAME,
          DATA_TYPE,
          IS_NULLABLE,
          COLUMN_DEFAULT,
          COLUMN_COMMENT,
          COLUMN_KEY,
          EXTRA
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
        ORDER BY ORDINAL_POSITION
      `, [dbConfig.database, tableName]);

            // 获取表的索引信息
            const [indexes] = await connection.execute(`
        SELECT 
          INDEX_NAME,
          COLUMN_NAME,
          NON_UNIQUE,
          SEQ_IN_INDEX
        FROM information_schema.STATISTICS 
        WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
        ORDER BY INDEX_NAME, SEQ_IN_INDEX
      `, [dbConfig.database, tableName]);

            // 检查实体类定义是否匹配
            if (entityDefinitions[tableName]) {
                console.log(`   📊 实体类定义检查:`);
                const entityDef = entityDefinitions[tableName];

                for (const column of columns) {
                    const columnName = column.COLUMN_NAME;
                    const entityField = Object.keys(entityDef).find(key =>
                        key.toLowerCase() === columnName.toLowerCase() ||
                        key.replace(/([A-Z])/g, '_$1').toLowerCase() === columnName.toLowerCase()
                    );

                    if (entityField) {
                        const entityFieldDef = entityDef[entityField];
                        const dbType = column.DATA_TYPE;
                        const entityType = entityFieldDef.type;

                        // 类型匹配检查
                        let typeMatch = true;
                        if (entityType.includes('bigint') && !dbType.includes('bigint')) typeMatch = false;
                        if (entityType.includes('tinyint') && !dbType.includes('tinyint')) typeMatch = false;
                        if (entityType.includes('varchar') && !dbType.includes('varchar')) typeMatch = false;
                        if (entityType.includes('text') && !dbType.includes('text')) typeMatch = false;
                        if (entityType.includes('datetime') && !dbType.includes('datetime')) typeMatch = false;
                        if (entityType.includes('int') && !dbType.includes('int')) typeMatch = false;

                        const status = typeMatch ? '✅' : '❌';
                        console.log(`     ${status} ${columnName}: ${dbType} (DB) vs ${entityType} (Entity)`);
                    } else {
                        console.log(`     ⚠️  ${columnName}: 实体类中未定义此字段`);
                    }
                }
            } else {
                console.log(`   ⚠️  未找到对应的实体类定义`);
            }

            // 显示表的列信息
            console.log(`   📋 表结构:`);
            columns.forEach(column => {
                const keyInfo = column.COLUMN_KEY === 'PRI' ? '🔑' :
                    column.COLUMN_KEY === 'UNI' ? '🔒' :
                        column.COLUMN_KEY === 'MUL' ? '🔗' : '  ';
                const nullable = column.IS_NULLABLE === 'YES' ? 'NULL' : 'NOT NULL';
                const defaultVal = column.COLUMN_DEFAULT ? `DEFAULT ${column.COLUMN_DEFAULT}` : '';
                console.log(`     ${keyInfo} ${column.COLUMN_NAME}: ${column.DATA_TYPE} ${nullable} ${defaultVal} ${column.COLUMN_COMMENT ? `// ${column.COLUMN_COMMENT}` : ''}`);
            });

            // 显示表的索引信息
            if (indexes.length > 0) {
                console.log(`   🔍 索引信息:`);
                const indexGroups = {};
                indexes.forEach(index => {
                    if (!indexGroups[index.INDEX_NAME]) {
                        indexGroups[index.INDEX_NAME] = [];
                    }
                    indexGroups[index.INDEX_NAME].push(index.COLUMN_NAME);
                });

                Object.entries(indexGroups).forEach(([indexName, columns]) => {
                    const isUnique = indexes.find(idx => idx.INDEX_NAME === indexName)?.NON_UNIQUE === 0;
                    const icon = isUnique ? '🔒' : '🔍';
                    console.log(`     ${icon} ${indexName}: [${columns.join(', ')}]`);
                });
            }

            console.log('');
        }

        // 检查是否有缺失的表
        console.log('🔍 检查缺失的表...');
        const expectedTables = Object.keys(entityDefinitions);
        const existingTables = tables.map(t => t.TABLE_NAME);
        const missingTables = expectedTables.filter(table => !existingTables.includes(table));

        if (missingTables.length > 0) {
            console.log('❌ 缺失的表:');
            missingTables.forEach(table => console.log(`   - ${table}`));
        } else {
            console.log('✅ 所有预期的表都已存在！');
        }

        // 检查表数据
        console.log('\n📊 检查表数据...');
        for (const table of tables) {
            const tableName = table.TABLE_NAME;
            const [count] = await connection.execute(`SELECT COUNT(*) as count FROM ${tableName}`);
            console.log(`   ${tableName}: ${count[0].count} 条记录`);
        }

    } catch (error) {
        console.error('❌ 检查过程中发生错误:', error.message);
    } finally {
        if (connection) {
            await connection.end();
            console.log('\n🔌 数据库连接已关闭');
        }
    }
}

// 运行检查
checkDatabaseSchema().catch(console.error); 